package cn.hrc.config;
import cn.hrc.dao.MyUserMapper;
import cn.hrc.entity.MyUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    MyUserMapper myUserDao;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
// user 浏览器扥路窗口输入账号 v-model ="username"
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("网页账号:"+username);
        QueryWrapper<MyUser> wrapper = new QueryWrapper<MyUser>()
                // 不写.select() 查询所有字段
                // 查询条件【eq】 ccount = #{username}
                .eq("account",username);
        logger.info("开始查询");
        MyUser m = myUserDao.selectOne(wrapper);
        logger.info("网页账号查询："+m);
        if (m == null)return null;
        logger.info("密码加密："+m.getPassword());

        //提供 UserDetails 的 实现类 User
        logger.info("身份："+m.getRole());

        GrantedAuthority p1 = new SimpleGrantedAuthority(m.getRole());
//        GrantedAuthority p2 = new SimpleGrantedAuthority(m.get("clz").toString());
        // 权限集合
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(p1); //list.add(p2);
        // 返回一个 UserDetails 的实现类
        UserDetails u = new User(username, m.getPassword(), list);
        logger.info("UserDetails: "+u.toString());
        return u;

    }
    
}
